﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Ruleweaver.Conditions;

namespace Ruleweaver.Conditions
{
	public static class DefaultConditionNames
	{
		public static IEnumerable<IConditionDeclaration> WithDefaultName<TDeclaration>(
			this IEnumerable<TDeclaration> declarations,
			string defaultConditionName)
			where TDeclaration : IConditionDeclaration
		{
			Contract.Requires(declarations != null);
			Contract.Requires(defaultConditionName != null);

			return declarations.Select(declaration => new DeclarationWithDefaultName(declaration, defaultConditionName));
		}

		private sealed class DeclarationWithDefaultName : IConditionDeclaration
		{
			private readonly IConditionDeclaration _declaration;
			private readonly string _defaultName;

			internal DeclarationWithDefaultName(IConditionDeclaration declaration, string defaultName)
			{
				_declaration = declaration;
				_defaultName = defaultName;
			}

			#region IConditionDeclaration

			public IEnumerable<Condition> GetConditions(Type targetType)
			{
				foreach(var condition in _declaration.GetConditions(targetType))
				{
					yield return !condition.Key.IsDefault
						? condition
						: new Condition(condition.Rule, condition.Key.TargetType, _defaultName);
				}
			}
			#endregion
		}
	}
}